<template>
    <div>
        <header>
            <van-nav-bar title="选择城市">
                <template #left>
                    <van-icon name="cross" size="18" @click="handleBack" />
                </template>
            </van-nav-bar>

            <form action="/">
                <van-search v-model="value" show-action placeholder="请输入搜索关键词" @search="onSearch" @cancel="onCancel" />
            </form>
        </header>




        <section>
            <van-index-bar :index-list="indexList" :sticky="false">
                <template v-for="item in citilist" :key="item.type">
                    <van-index-anchor :index="item.type" style="background-color: #F4F4F4;"/>
                    <van-cell :title="data.name" v-for="data in item.list" :key="data.cityId" @click="handleChange(data)" />
                </template>
            </van-index-bar>
        </section>
    </div>
</template>

<script setup>
import axios from 'axios';
import { computed, onMounted, ref } from 'vue';
import _ from 'lodash';
import { IndexBar as vanIndexBar, IndexAnchor as vanIndexAnchor, Cell as vanCell, NavBar as vanNavBar, Icon as vanIcon, Search as vanSearch } from 'vant';
import useCityStore from '../store/cityStore'
import { useRouter } from 'vue-router'
const router = useRouter()
const store = useCityStore()
const citilist = ref([])
const indexList = computed(() => citilist.value.map(item => item.type))

const onSearch = () => {
    console.log('开始搜索');
}
const onCancel = () => {
    console.log('取消搜素');
}


onMounted(async () => {
    let res = await axios({
        url: 'https://m.maizuo.com/gateway?k=960562',
        headers: {
            'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.2.1","e":"17089542072373175589470209","bc":"110100"}',
            'X-Host': 'mall.film-ticket.city.list',
        }
    })
    citilist.value = filterCity(res.data.data.cities)
    console.log(citilist.value)
})
// 城市列表 根据大写字母分组分组
const filterCity = (cities) => {
    cities.sort((item1, item2) => item1.pinyin.substring(0, 1).toUpperCase().charCodeAt() - item2.pinyin.substring(0, 1).toUpperCase().charCodeAt())
    let clist = _.groupBy(cities, item => item.pinyin.substring(0, 1).toUpperCase())
    let newCities = []
    for (let i in clist) {
        // console.log(i);
        newCities.push({
            'type': i,
            'list': clist[i]
        })
    }
    return newCities
}
const handleChange = ({ name, cityId }) => {
    console.log(name, cityId);
    store.change(name, cityId)
    router.go(-1)
}
const handleBack = () => {
    router.go(-1)
}
</script>

<style lang="scss" scoped>
header{
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 100;
}
section{
    
}
</style>
